<template>
    <div class="meetings-section">
        <div class="section-header">
            <h2>会议管理</h2>
            <el-button type="primary" @click="showCreateMeetingDialog = true">📅 创建会议</el-button>
        </div>

        <div class="table-container">
            <el-table :data="mockMeetings" style="width: 100%">
                <el-table-column prop="name" label="会议名称" min-width="200" />
                <el-table-column prop="startTime" label="开始时间" width="150" />
                <el-table-column prop="endTime" label="结束时间" width="150" />
                <el-table-column prop="creator" label="创建人" width="120" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280">
                    <template #default="{ row }">
                        <el-button size="small" @click="viewMeeting(row)">查看</el-button>
                        <el-button size="small" @click="editMeeting(row)">编辑</el-button>
                        <el-button v-if="userType === 'admin' && row.status === 'pending'" size="small" type="success"
                            @click="approveMeeting(row)">
                            审核
                        </el-button>
                        <el-button size="small" type="danger" @click="deleteMeeting(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- View Meeting Details Dialog -->
        <el-dialog v-model="showDetailDialog" :title="detailTitle" width="800px">
            <div v-if="currentItem" class="detail-content">
                <div class="meeting-detail">
                    <h3>{{ currentItem.name }}</h3>
                    <div class="detail-info">
                        <p><strong>开始时间：</strong>{{ currentItem.startTime }}</p>
                        <p><strong>结束时间：</strong>{{ currentItem.endTime }}</p>
                        <p><strong>创建人：</strong>{{ currentItem.creator }}</p>
                        <p><strong>状态：</strong>
                            <el-tag :type="getStatusType(currentItem.status)">
                                {{ getStatusText(currentItem.status) }}
                            </el-tag>
                        </p>
                    </div>
                    <div class="cover-section">
                        <h4>会议封面：</h4>
                        <div class="image-placeholder" style="height: 200px;">
                            会议封面展示区域
                        </div>
                    </div>
                    <div class="content-section">
                        <h4>会议内容：</h4>
                        <p>{{ currentItem.content || '暂无会议内容' }}</p>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- Create/Edit Meeting Dialog -->
        <el-dialog v-model="showCreateMeetingDialog" :title="editingMeeting ? '编辑会议' : '创建会议'" width="600px"
            @closed="resetMeetingForm">
            <el-form :model="meetingForm" :rules="meetingRules" ref="meetingFormRef" label-width="100px">
                <el-form-item label="会议名称" prop="name">
                    <el-input v-model="meetingForm.name" placeholder="请输入会议名称" />
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="开始时间" prop="startTime">
                            <el-date-picker v-model="meetingForm.startTime" type="datetime" placeholder="选择开始时间"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束时间" prop="endTime">
                            <el-date-picker v-model="meetingForm.endTime" type="datetime" placeholder="选择结束时间"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="创建人" prop="creator">
                    <el-input v-model="meetingForm.creator" placeholder="请输入创建人" />
                </el-form-item>

                <el-form-item label="会议内容" prop="content">
                    <el-input v-model="meetingForm.content" type="textarea" :rows="4" placeholder="请输入会议内容和议程..." />
                </el-form-item>

                <el-form-item label="会议封面">
                    <div class="upload-area">
                        <div class="image-placeholder" @click="handleImageUpload">
                            📷 点击上传会议封面图片
                            <p style="font-size: 12px; color: #999; margin-top: 5px;">
                                支持 JPG、PNG 格式，建议尺寸 800x400
                            </p>
                        </div>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showCreateMeetingDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveMeeting" :loading="createLoading">
                        {{ editingMeeting ? '更新会议' : '创建会议' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    name: 'MeetingManagement',
    setup() {
        const userType = ref(localStorage.getItem('userType') || 'enterprise');
        const showCreateMeetingDialog = ref(false);
        const editingMeeting = ref(null);
        const meetingFormRef = ref();
        const createLoading = ref(false);
        const showDetailDialog = ref(false);
        const detailTitle = ref('');
        const currentItem = ref(null);

        const meetingForm = ref({
            name: '',
            startTime: null,
            endTime: null,
            creator: '',
            content: '',
            coverImage: ''
        });

        const meetingRules = {
            name: [{ required: true, message: '请输入会议名称', trigger: 'blur' }],
            startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
            endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
            creator: [{ required: true, message: '请输入创建人', trigger: 'blur' }],
            content: [{ required: true, message: '请输入会议内容', trigger: 'blur' }]
        };

        const mockMeetings = ref([
            { id: 1, name: '年度工作会议', startTime: '2024-06-25 09:00', endTime: '2024-06-25 17:00', creator: '管理员', status: 'approved', content: '讨论年度工作总结和下年度计划' },
            { id: 2, name: '技术交流会', startTime: '2024-06-28 14:00', endTime: '2024-06-28 16:00', creator: '技术部', status: 'pending', content: '分享最新技术趋势和解决方案' },
            { id: 3, name: '产品发布会', startTime: '2024-07-01 10:00', endTime: '2024-07-01 12:00', creator: '产品部', status: 'approved', content: '新产品功能介绍和演示' },
        ]);

        const getStatusText = (status) => {
            const texts = {
                pending: '待审核',
                approved: '已通过',
                rejected: '已拒绝'
            };
            return texts[status] || status;
        };

        const getStatusType = (status) => {
            const types = {
                pending: 'warning',
                approved: 'success',
                rejected: 'danger'
            };
            return types[status] || 'info';
        };

        const formatDateTime = (date) => {
            if (!date) return '';
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            }).replace(/\//g, '-');
        };

        const viewMeeting = (meeting) => {
            currentItem.value = meeting;
            detailTitle.value = '会议详情';
            showDetailDialog.value = true;
        };

        const editMeeting = (meeting) => {
            editingMeeting.value = meeting;
            meetingForm.value = {
                name: meeting.name,
                startTime: new Date(meeting.startTime),
                endTime: new Date(meeting.endTime),
                creator: meeting.creator,
                content: meeting.content
            };
            showCreateMeetingDialog.value = true;
        };

        const deleteMeeting = async (meeting) => {
            try {
                await ElMessageBox.confirm(`确定要删除会议 "${meeting.name}" 吗？`, '确认删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const index = mockMeetings.value.findIndex(item => item.id === meeting.id);
                if (index !== -1) {
                    mockMeetings.value.splice(index, 1);
                    ElMessage.success('会议删除成功');
                }
            } catch (error) {
                // User cancelled delete
            }
        };

        const approveMeeting = async (meeting) => {
            try {
                await ElMessageBox.confirm('确定要审核通过这个会议吗？', '确认操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const index = mockMeetings.value.findIndex(item => item.id === meeting.id);
                if (index !== -1) {
                    mockMeetings.value[index].status = 'approved';
                    ElMessage.success('会议审核通过');
                }
            } catch (error) {
                // User cancelled operation
            }
        };

        const resetMeetingForm = () => {
            meetingForm.value = {
                name: '',
                startTime: null,
                endTime: null,
                creator: '',
                content: '',
                coverImage: ''
            };
            editingMeeting.value = null;
        };

        const saveMeeting = async () => {
            try {
                await meetingFormRef.value.validate();
                if (meetingForm.value.startTime >= meetingForm.value.endTime) {
                    ElMessage.error('结束时间必须晚于开始时间');
                    return;
                }
                createLoading.value = true;
                await new Promise(resolve => setTimeout(resolve, 1000));

                if (editingMeeting.value) {
                    const index = mockMeetings.value.findIndex(item => item.id === editingMeeting.value.id);
                    if (index !== -1) {
                        mockMeetings.value[index] = {
                            ...mockMeetings.value[index],
                            name: meetingForm.value.name,
                            startTime: formatDateTime(meetingForm.value.startTime),
                            endTime: formatDateTime(meetingForm.value.endTime),
                            creator: meetingForm.value.creator,
                            content: meetingForm.value.content
                        };
                    }
                    ElMessage.success('会议更新成功！');
                } else {
                    const newMeeting = {
                        id: Date.now(),
                        name: meetingForm.value.name,
                        startTime: formatDateTime(meetingForm.value.startTime),
                        endTime: formatDateTime(meetingForm.value.endTime),
                        creator: meetingForm.value.creator,
                        content: meetingForm.value.content,
                        status: 'pending'
                    };
                    mockMeetings.value.unshift(newMeeting);
                    ElMessage.success('会议创建成功！');
                }
                showCreateMeetingDialog.value = false;
            } catch (error) {
                ElMessage.error('请填写完整的会议信息');
            } finally {
                createLoading.value = false;
            }
        };

        const handleImageUpload = () => {
            ElMessage.info('图片上传功能开发中...');
        };

        return {
            userType,
            mockMeetings,
            showCreateMeetingDialog,
            editingMeeting,
            meetingFormRef,
            meetingForm,
            meetingRules,
            createLoading,
            showDetailDialog,
            detailTitle,
            currentItem,
            getStatusText,
            getStatusType,
            viewMeeting,
            editMeeting,
            deleteMeeting,
            approveMeeting,
            saveMeeting,
            resetMeetingForm,
            handleImageUpload,
        };
    }
};
</script>

<style scoped>
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-header h2 {
    margin: 0;
    color: #333;
}

.table-container {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.upload-area {
    margin-top: 10px;
}

.image-placeholder {
    width: 100%;
    height: 120px;
    border: 2px dashed #ddd;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    color: #666;
}

.image-placeholder:hover {
    border-color: #409eff;
    color: #409eff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.detail-content h3 {
    margin-bottom: 20px;
    color: #333;
    border-bottom: 2px solid #f0f0f0;
    padding-bottom: 10px;
}

.detail-content h4 {
    margin: 20px 0 10px 0;
    color: #666;
}

.detail-info p {
    margin: 10px 0;
    color: #666;
}

.cover-section,
.content-section {
    margin-bottom: 20px;
}
</style>